using B.S.XZYData.Api.Wrter.Application.Command.Route;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Route
{
    /// <summary>
    /// 删除工艺路线处理器
    /// </summary>
    public class DeleteRouteHandler : IRequestHandler<DeleteRouteCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<RouteModel> _routeRepository;
        private readonly IBaseRepository<RouteStepModel> _routeStepRepository;
        private readonly ILogger<DeleteRouteHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        public DeleteRouteHandler(
            IBaseRepository<RouteModel> routeRepository,
            IBaseRepository<RouteStepModel> routeStepRepository,
            ILogger<DeleteRouteHandler> logger)
        {
            _routeRepository = routeRepository;
            _routeStepRepository = routeStepRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理删除工艺路线命令
        /// </summary>
        public async Task<ApiResult<bool>> Handle(DeleteRouteCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 检查工艺路线是否存在
                var route = await _routeRepository.GetValue(request.RouteId);
                if (route == null)
                {
                    return new ApiResult<bool> { Msg = "工艺路线不存在", Code = ApiEnum.Fail, Data = false };
                }

                // 删除相关的工序
                var steps = _routeStepRepository.GetAll().Where(x => x.RouteId == request.RouteId).ToList();
                if (steps.Any())
                {
                    await _routeStepRepository.DeleteBatchAsync(steps);
                }

                // 删除工艺路线
                await _routeRepository.DeleteAsync(request.RouteId);

                _logger.LogInformation($"删除工艺路线成功，RouteId: {request.RouteId}, OperateBy: {request.OperateBy}");
                return new ApiResult<bool> { Msg = "删除工艺路线成功", Code = ApiEnum.Success, Data = true };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除工艺路线失败，RouteId: {request.RouteId}");
                return new ApiResult<bool> { Msg = "删除工艺路线失败", Code = ApiEnum.Fail, Data = false };
            }
        }
    }
} 